package com.alog.yzd.jdbc.hm;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;

class MyConnectionHandler implements InvocationHandler {

    private Connection realConn;
    private MyDataSource dataSource;
    private Connection wrapperConn;

    private int maxUseCount = 15;
    private int currentUseCount = 0;
    MyConnectionHandler(MyDataSource ds){
        dataSource = ds;
    }


    Connection bind(Connection conn){
        realConn = conn;
        wrapperConn = (Connection) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[]{Connection.class}, this);
        return  wrapperConn;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if("close".equals(method.getName())){
            currentUseCount++;
            if(currentUseCount < maxUseCount){
                dataSource.free(wrapperConn);
            } else {
                realConn.close();
                dataSource.currentCounts--;
            }
            return null;
        }
        return method.invoke(realConn, args);
    }
}
